//@author A0096566M
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "windows.h"
#include <QDebug>
#include <QCompleter>
#include <QLabel>
#include <Qtimer>
#include <QStandardItemModel>

void MainWindow::mousePressEvent(QMouseEvent* event)
{
    if(event->button() == Qt::LeftButton)
    {
        mMoving = true;
        mLastMousePosition = event->pos();
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent* event)
{
    if( event->buttons().testFlag(Qt::LeftButton) && mMoving)
    {
        this->move(this->pos() + (event->pos() - mLastMousePosition));
    }
}

void MainWindow::mouseReleaseEvent(QMouseEvent* event)
{
    if(event->button() == Qt::LeftButton)
    {
        mMoving = false;
    }
}

void MainWindow::myslot(){
    this->activateWindow();
    this->raise();
    this->setFocus();
    te->setFocus();
}

void MainWindow::showhide(DWORD key, DWORD alt){
    if(key == 123 && alt!= 1){//alt - alternate key not down.
        if (isVisible()){
            mcompleter->popup()->hide();
            for(int i=100 ; i>=0 ; i--){
                Sleep(5);
                this->setWindowOpacity(qreal(i)/100);
            }
            hide();
        }
        else{
            show();
            QTimer* m_myLongTimer = new QTimer(this);
            m_myLongTimer->setInterval(0);
            m_myLongTimer->setSingleShot(true);
            connect(m_myLongTimer, SIGNAL(timeout()), SLOT(myslot()));
            m_myLongTimer->start();

            for(int i=0 ; i<100 ; i++){
                Sleep(5);
                this->setWindowOpacity(qreal(i)/100);
            }

        }
    }
    //For keyboard scrolling
    qDebug() << key;
    //36 home
    //33 pgup
    //34 pgdown
    //35 end
    if(isVisible()){
        //Home
        if(key == 36){
            QScrollBar *v = this->ui->textBrowser->verticalScrollBar();
            v->setValue(v->minimum());
        }
        //End
        if(key == 35){
            QScrollBar *v = this->ui->textBrowser->verticalScrollBar();
            v->setValue(v->maximum());
        }
        //pgup
        if(key == 33){
            QScrollBar *v = this->ui->textBrowser->verticalScrollBar();
            v->setValue(v->value() - v->height());
        }
        //pgdown
        if(key == 34){
            QScrollBar *v = this->ui->textBrowser->verticalScrollBar();
            v->setValue(v->value() + v->height());
        }
    }
}


void MainWindow::enterPressed(){
    //Send input to taak
        //Normal input.
    this->selectedIndex = this->mcompleter->selectedIndex;
    if(selectedIndex >=0 && selectedIndex<taak.getParser().getCommandList().size())
        this->selectedCommand = taak.getParser().getCommandList()[selectedIndex];
    qDebug() << "Sel Index: " << this->selectedIndex;

    if(this->selectedIndex == -1){
        if(strcmp(this->te->toPlainText().toStdString().c_str(),"")!=0)
            taak.userInput(this->te->toPlainText().toHtmlEscaped().toStdString());
    } else {
        qDebug() << "Using Suggestion.";
        //Use selected suggestion
        if(strcmp(this->te->toPlainText().toStdString().c_str(),"")!=0){
            taak.userSuggestionInput(this->te->toPlainText().toStdString(), selectedCommand);
            this->selectedIndex = -1;
        }
    }

    //Display all stuff from taak
    this->ui->textBrowser->setText(QString::fromStdString(taak.getMainDisplayTitle()) + QString::fromStdString(taak.getMainDisplay()));
    this->ui->textBrowser_2->setText(QString::fromStdString(taak.getStatusDisplay()));

    //Input history
    this->mcompleter->inputHistory.insert(this->mcompleter->inputHistory.begin(),this->te->toPlainText().toHtmlEscaped().toStdString());

    //Clear input
    this->te->setText("");
    if(taak.getInputDisplay()!=""){
        this->te->setText(QString::fromStdString(taak.getInputDisplay()));
        this->te->setText(this->te->toPlainText().toHtmlEscaped());
        taak.setInputDisplay("");
    }
}

void MainWindow::textChanged(){

    /*
     *  Because textChanged is activated even when the user selects a suggestion,
     *  so this method is used.
     */

    if(this->te->toPlainText() != prev){
        qDebug() << "Text changed." << this->te->toPlainText();
        this->selectedIndex = -1;
        this->selectedIndex = this->mcompleter->selectedIndex;
        if(selectedIndex >=0 && selectedIndex<taak.getParser().getCommandList().size())
            this->selectedCommand = taak.getParser().getCommandList()[selectedIndex];
        //this->mcompleter->selectedIndex = -1;
        prev = this->te->toPlainText();
    } else {
    }
        taak.userCharInput(te->toPlainText().toHtmlEscaped().toStdString());
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    //Initialize Taak
    taak.initialize();

    //UI setup
    ui->setupUi(this);
    setAttribute(Qt::WA_TranslucentBackground);
    setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);

    //Setup Input box
    this->ui->lineEdit->hide();
    te = new MyLineEdit(this);
    te->setProperty("geometry",ui->lineEdit->property("geometry"));
    this->te->setStyleSheet("font: 10pt \"Cambria\";       color: rgb(51, 51, 51);            -webkit-transition-property: border, box-shadow;          -webkit-rtl-ordering: logical;            -webkit-transition-delay: 0s, 0s;            -webkit-transition-duration: 0.2s, 0.2s;            -webkit-appearance: none;            -webkit-box-shadow: rgba(0, 0, 0, 0.0745098) 0px 1px 1px 0px inset, rgba(84, 168, 236, 0.427451) 0px 0px 6px 0px;            -webkit-transition-timing-function: linear, linear;            -webkit-user-select: text;            -webkit-writing-mode: horizontal-tb;            background-color: rgb(255, 255, 255);            border-bottom-color: rgba(123, 180, 224, 0.858824);            border-bottom-left-radius: 4px;            border-bottom-right-radius: 4px;            border-bottom-style: solid;            border-bottom-width: 1px;            border-image-outset: 0px;            border-image-repeat: stretch;            border-image-slice: 100%;            border-image-source: none;            border-image-width: 1;            border-left-color: rgba(123, 180, 224, 0.858824);            border-left-style: solid;            border-left-width: 1px;            border-right-color: rgba(123, 180, 224, 0.858824);            border-right-style: solid;            border-right-width: 1px;            border-top-color: rgba(123, 180, 224, 0.858824);            border-top-left-radius: 4px;            border-top-right-radius: 4px;            border-top-style: solid;            border-top-width: 1px;            box-shadow: rgba(0, 0, 0, 0.0745098) 0px 1px 1px 0px inset, rgba(84, 168, 236, 0.427451) 0px 0px 6px 0px;            color: rgb(85, 85, 85);            cursor: auto;            height: 20px;            letter-spacing: normal;            line-height: 20px;            margin-left: 0px;            margin-right: 0px;            margin-top: 0px;            text-align: start;            text-indent: 0px;            text-shadow: none;            text-transform: none;            transition-delay: 0s, 0s;            transition-duration: 0.2s, 0.2s;            transition-property: border, box-shadow;            transition-timing-function: linear, linear;            vertical-align: middle;            word-spacing: 0px;            writing-mode: lr-tb;");
    te->setFocus();

    //Setup MyCompleter
    mcompleter = new MyCompleter(QStringList(),this);
    mcompleter->setCaseSensitivity(Qt::CaseInsensitive);
    mcompleter->taak = &this->taak;
    te->setCompleter(mcompleter);
    te->show();
    prev = te->toPlainText();

    //Connect Keyboard Hook.
    syskey.setConnected(true);
    QObject::connect(syskey.instance(), SIGNAL(keyPressed(DWORD,DWORD)), this, SLOT(showhide(DWORD,DWORD)));

    //Connect enterPressed()
    QObject::connect(this->te, SIGNAL(returnPressed()), this, SLOT(enterPressed()));
    //Connect textChanged()
    QObject::connect(this->te, SIGNAL(textChanged()), this, SLOT(textChanged()));

    //Set Initial Text
    this->te->setText("");//Display all stuff from taak
    this->ui->textBrowser->setText(QString::fromStdString(taak.getMainDisplayTitle()) + QString::fromStdString(taak.getMainDisplay()));
    this->ui->textBrowser_2->setText(QString::fromStdString(taak.getStatusDisplay()));
    this->ui->textBrowser->setStyleSheet(QString::fromUtf8("QScrollBar:vertical { border: 0px solid #999999; background:white; width:10px; margin: 0px 0px 0px 0px; } QScrollBar::handle:vertical { background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop: 0 rgb(255, 255, 255), stop: 0.5 rgb(200, 200, 255), stop:1 rgb(255, 255, 255)); min-height: 0px; border-top-left-radius: 4px; border-top-right-radius: 4px; } QScrollBar::sub-line:vertical { background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop: 0 rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130), stop:1 rgb(32, 47, 130)); height: 0px; subcontrol-position: top; subcontrol-origin: margin; }"));

    setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
}

bool MainWindow::eventFilter(QObject *object, QEvent *event)
{

    setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
    if (event->type() == QEvent::FocusIn )
    {
        QTimer* m_myLongTimer = new QTimer(this);
        m_myLongTimer->setInterval(0);
        m_myLongTimer->setSingleShot(true);
        connect(m_myLongTimer, SIGNAL(timeout()), SLOT(myslot()));
        m_myLongTimer->start();
    }
    return false;
}

MainWindow::~MainWindow()
{
    syskey.setConnected(false);
    delete ui;
}
